package server

import (
	"context"
	"errors"
	"fmt"
	"longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/redis/cache"
	pb "longmen/server/pkg/protobuf"
	"strings"
	"time"
)

// 踢人的方法
// 去cache中把缓存改掉
// 让他一小时不能登陆
func (s *Server) Logout(ctx context.Context, req *pb.LogoutReq) (*pb.LogoutResp, error) {
	user, err := mysql.GetUserParam(map[string]interface{}{"id": req.Uid})
	if err != nil || user.Id == 0 {
		return nil, errors.New("uid not found")
	}
	sToken, err := cache.GetUserTokenLua(int(req.Uid))
	err = cache.SetUserToken(int(req.Uid), _const.TOKEN_KICKED_OUT, 0)
	err = cache.SetUserToken(int(req.Uid), _const.TOKEN_KICKED_OUT, 1)
	if err != nil {
		return nil, err
	}
	if req.Ban == 0 {
		if sToken == "" || strings.HasSuffix(sToken, _const.TOKEN_KICKED_OUT) || strings.HasPrefix(sToken, _const.TOKEN_KICKED_OUT) {
			return &pb.LogoutResp{Code: _const.RPC_SUCCEED, Info: fmt.Sprintf("%d is not online", req.Uid)}, nil
		}
		user.OnlineStatus = 9
		user.BlockUntilTime = time.Now().Add(1 * time.Hour)
		user.Status = _const.ACCOUNT_STATUS_KICKED_OUT //1小时不让登陆
		if err := db_main.UpdateUser([]string{"status", "online_status", "block_until_time"}, user); err != nil {
			return nil, err
		}
	}
	//cache.SendWsGoodBye(user.Id)去聊天室将他踢出
	return &pb.LogoutResp{Code: _const.RPC_SUCCEED, Info: fmt.Sprintf("%d is kicked out", req.Uid)}, nil
}
